<template>
  <dv-border-box-1 style="height:630px">
    <div id="border">
      <!-- 表单 -->
      <el-form :inline="true" width="100%" :model="searchMap" class="demo-form-inline">
        <el-form-item>
          <el-input v-model="searchMap.cname" placeholder="分类名"></el-input>
        </el-form-item>
        <el-form-item label="分类状态" prop="state">
          <el-select size="small" width="50" v-model="searchMap.state" placeholder="请选择">
            <el-option
              v-for="item in StateOptionsOfSearch"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="fetchData">查询</el-button>
        </el-form-item>
        <el-button
          v-if="!isDialog"
          style="float:right"
          icon="el-icon-plus"
          type="primary"
          circle
          @click="handleAdd"
        ></el-button>
      </el-form>
      <el-row :gutter="20">
        <el-col :span="!isDialog ? 17 : 24">
          <div>
            <!-- Table -->
            <el-table
              :highlight-current-row="isDialog"
              @current-change="clickCurrentChange"
              :data="list"
              style="width: 100%"
              height="460"
            >
              <el-table-column type="index" label="序号" width="50"></el-table-column>
              <el-table-column prop="id" label="分类编号" width="150"></el-table-column>
              <el-table-column prop="cname" label="分类名" width="120"></el-table-column>
               <el-table-column prop="level" label="分类等级" width="120"></el-table-column>
              <el-table-column prop="state" label="状态" width="120">
                <template slot-scope="scope">
                  <el-tag :type="scope.row.state === '1' ? '' : 'info'">
                    {{
                    scope.row.state | stateFilter
                    }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="parentId" label="父类目id" width="170"></el-table-column>
              <el-table-column prop="isparent" label="是否为父类目" width="120">
                <template slot-scope="scope">
                  <el-tag :type="scope.row.isparent === '1' ? '' : 'info'">
                    {{
                    scope.row.isparent === '1' ? '是' : '否'
                    }}
                  </el-tag>
                </template>
              </el-table-column>

              <el-table-column v-if="!isDialog" label="操作" fixed="right" width="120px">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="primary"
                    icon="el-icon-edit"
                    circle
                    @click="handleEdit(scope.row.id)"
                  ></el-button>
                  <el-button
                    size="mini"
                    type="danger"
                    icon="el-icon-delete"
                    circle
                    @click="handleDelete(scope.row.id,scope.row.isparent)"
                  ></el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-divider></el-divider>
            <!-- 分页 -->
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[5, 10, 15, 20]"
              :page-size="pageSize"
              :layout="
                !isDialog
                  ? 'total, sizes, prev, pager, next, jumper'
                  : 'prev,pager,next'
              "
              :total="total"
            ></el-pagination>
          </div>
        </el-col>
        <el-col :span="7" v-if="!isDialog">
          <!-- 图片 -->

          <!-- 卡片 -->
          <el-card :body-style="{ padding: '0px' }" style="height:500px">
            <el-tree :data="treeData" node-key="id" accordion :expand-on-click-node="false">
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <span>{{ node.data.cname }}</span>
                <span>
                  <el-button type="text" size="mini" @click="() => append(data)">+</el-button>
                  <el-button
                    type="text"
                    icon="el-icon-delete"
                    size="mini"
                    @click="() => remove(node, data)"
                  ></el-button>
                </span>
              </span>
            </el-tree>
          </el-card>
        </el-col>
      </el-row>

      <!-- 编辑标签Dialog -->
      <el-dialog title="编辑分类" :visible.sync="dialogFormVisible" width="400px">
        <el-form
          :model="pojo"
          ref="pojoForm"
          :rules="rules"
          label-position="right"
          label-width="80px"
          size="mini"
        >
          <el-form-item label="分类名称" prop="cname">
            <el-input width="60px" v-model="pojo.cname" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="状态" prop="state">
            <el-tooltip :content="pojo.state === '1' ? '使用中' : '添加使用'" placement="top">
              <el-switch
                v-model="pojo.state"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :disabled="pojo.state==='1'"
                active-value="1"
                inactive-value="0"
                @change="handleStateChange"
              ></el-switch>
            </el-tooltip>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="
              pojo.id === null ? addData() : updateData('pojoForm')
            "
          >{{ this.pojo.id === null ? "添加" : "修改" }}</el-button>
        </div>
      </el-dialog>
    </div>
  </dv-border-box-1>
</template>
<script>
import categoryApi from "@/api/category";
const stateTypeOptions = [
  { type: "0", name: "已弃用" },
  { type: "1", name: "使用中" }
];
let id = 1000;
export default {
  props: {
    //接收父组件传递过来的数据，通过isDialog判断是否为弹框 true为弹框
    isDialog: Boolean
  },
  data() {
    return {
      StateOptionsOfSearch: [
        {
          value: "2",
          label: "全部"
        },
        {
          value: "1",
          label: "正常"
        },
        {
          value: "0",
          label: "异常"
        }
      ],
      treeData: [],
      currentDate: new Date(),
      list: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      searchMap: {
        cname: ""
      },
      dialogFormVisible: false, //控制dialog显示
      rules: {
        cname: [
          { required: true, message: "分类名称不能为空", trigger: "blur" }
        ]
      },
      pojo: {
        id: null,
        cname: "",
        state: "",
        parentId: ""
      }
    };
  },
  created() {
    this.fetchData();
    this.fetchCategoryTree();
  },
  methods: {
    fetchCategoryTree() {
      categoryApi.fetchCategoryTree().then(resp => {
        if (resp.data.flag) {
          this.treeData = JSON.parse(JSON.stringify(resp.data.data));
          //console.log(this.treeData)
        }
      });
    },
    /**
     * Tree中添加分类
     */
    append(data) {
      console.log("data", data);
      this.handleAdd();

      this.pojo.parentId = data.id;
    },
    /**
     * Tree中弃用分类
     */
    remove(node, data) {
      //  console.log(node)
      this.handleDelete(node.data.id, node.data.isparent);
    },
    fetchData() {
      categoryApi
        .searchPage(this.currentPage, this.pageSize, this.searchMap)
        .then(resp => {
          const respData = resp.data;
          if (respData.flag) {
            this.list = respData.data.rows;
            //  console.log(this.list)
            this.total = respData.data.total;
          } else {
            this.$message({
              message: respData.message,
              type: "warning"
            });
          }
        });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchData();
    },
    /**
     * 打开编辑标签窗口
     */
    handleAdd() {
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["pojoForm"].resetFields();
      });
      this.pojo.parentId = "";
    },
    /**
     * 添加标签
     */
    addData() {
      this.$refs.pojoForm.validate(valid => {
        if (valid) {
          categoryApi.addCategory(this.pojo).then(resp => {
            const respData = resp.data;
            if (respData.flag) {
              this.$message({
                message: respData.message,
                type: "success"
              });
              this.fetchData();
              this.fetchCategoryTree();
              this.dialogFormVisible = false;
            } else {
              this.$message({
                message: respData.message,
                type: "warning"
              });
            }
          });
        } else {
          this.$message({
            message: "分类名不能为空",
            type: "warning"
          });
        }
      });
    },
    /**
     * 打开编辑标签窗口
     */
    handleEdit(id) {
      this.handleAdd();
      categoryApi.getCategoryById(id).then(resp => {
        const respData = resp.data;
        if (respData.flag) {
          this.pojo = respData.data;
        } else {
          this.$message({
            message: respData.message,
            type: "error"
          });
        }
      });
    },
    /**
     * 更新标签
     */
    updateData(formName) {
      this.$refs.pojoForm.validate(valid => {
        if (valid) {
          //提交更新
          categoryApi.updateCategory(this.pojo).then(resp => {
            const respData = resp.data;
            if (respData.flag) {
              this.$message({
                message: respData.message,
                type: "success"
              });
              this.fetchData();
              this.fetchCategoryTree();
              this.dialogFormVisible = false;
            } else {
              this.$message({
                message: respData.message,
                type: "warning"
              });
            }
          });
        } else {
          this.$message({
            message: "分类不能为空",
            type: "warning"
          });
        }
      });
    },
    /**
     * 删除标签
     */
    handleDelete(id, isparent) {
      this.$confirm("确定弃用此分类吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          categoryApi.deleteById(id, isparent).then(resp => {
            this.$message({
              type: resp.data.flag ? "success" : "error",
              message: "删除成功!"
            });
            if (resp.data.flag) {
              this.fetchData();
              this.fetchCategoryTree();
            }
          });
        })
        .catch(() => {
          return;
        });
    },

    handleStateChange(val) {
      this.pojo.state = val;
    },
    /**
     * 查询的状态改变时触发
     */
    handleSearchStateChange(val) {
      this.searchMap.state = val;
    },
    /**
     * 点击某行后触发该方法
     */
    clickCurrentChange(currentRow) {
      this.$emit("option-category", currentRow);
    }
  },
  filters: {
    stateFilter(type) {
      const stateobj = stateTypeOptions.find(obj => {
        return obj.type === type;
      });
      return stateobj ? stateobj.name : null;
    }
  }
};
</script>
<style scoped>
#border {
  padding: 20px;
}
/* 图片 */
.time {
  font-size: 13px;
  color: #999;
}

.bottom {
  margin-top: 13px;
  line-height: 12px;
}

.button {
  padding: 0;
  float: right;
}

.image {
  width: 100%;
  display: block;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
